package com.poetize.plus.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.poetize.plus.utils.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 *
 * security登录失败处理器
 *
 * @author zuosy
 * @created 2024/3/28 15:54
 */
@Component
@RequiredArgsConstructor
public class LoginFiledHandler implements AuthenticationFailureHandler {

    private final ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //1.设置响应编码
        response.setContentType("application/json;charset=UTF-8");
        String str = "";
        if (exception instanceof BadCredentialsException){
            str = "用户名或密码错误，登录失败!";
        }
        if (exception instanceof DisabledException){
            str = "账户被禁用，登录失败!";
        }
        ServletOutputStream out = response.getOutputStream();
        R<String> fail = R.failForCodeMsg(500, str);
        out.write(objectMapper.writeValueAsString(fail).getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
